var request = require('request');
var moment = require('moment');
var fs = require('fs');
var path = require('path');
var exec = require('child_process').exec;

moment.locale('zh-cn');
var utils = {
    getFilePath(fn) {
        var me = this;
        var res = "";
        try {
            res = path.parse(fn).dir;
        } catch (Exce) {
            console.log(Exce);
        }
        return res;
    },
    craetePath(pathName) {
        var me = this;
        var res = "";
        try {
            if (fs.existsSync(pathName)) {
                res = pathName;
            } else {
                var parentPathname = path.resolve(pathName, "..");
                var flag = me.craetePath(parentPathname);
                fs.mkdirSync(pathName);
            }
        } catch (Exce) {
            console.log(Exce);
        }
        return res;
    },
    writeFile(fn, content) {
        var me = this;
        try {
            var fpath = path.resolve(path.parse(fn).dir);
            me.craetePath(fpath);
            fs.writeFileSync(fn, content);
        } catch (Exce) {
            console.log(Exce);
        }
        return fs.existsSync(fn);
    },
    readFile(fn, content) {
        var me = this;
        var res = "";
        try {
            if (fs.existsSync(fn)) {
                res = fs.readFileSync(fn);
            }
        } catch (Exce) {
            console.log(Exce);
        }
        return res;
    },
    httpCall(aUrl, aMethod, aHeaders, aPs, aBody) {
        var me = this;
        return new Promise((success, faild) => {
            try {
                var callUrl = aUrl;
                if (aPs && aPs != null && Object.keys(aPs) && Object.keys(aPs).length > 0) {
                    callUrl += callUrl.indexOf("?") > 0 ? "&" : "?";
                    callUrl += "randtm=" + Math.random();
                    Object.keys(aPs).forEach(p => {
                        callUrl += "&" + p + "=" + aPs[p];
                    })
                }

                var opts = {
                    url: callUrl,
                    method: aMethod
                }

                if (aBody && aBody != null) {
                    opts.body = aBody;
                }

                request(opts, (err, resp, result) => {
                    success({
                        err: err,
                        resp: resp,
                        result: result
                    })
                })
            } catch (Exce) {
                console.log(Exce);
                success(null);
            }
        })
    },
    writeDB(aDbUrl, dbName, tableName, tags, fields, timestampe) {
        var me = this;
        return new Promise((success, faild) => {
            try {
                var ps = {
                    db: dbName
                };
                var tagDatas = [];
                Object.keys(tags).forEach(t => {
                    tagDatas.push(t + "=" + tags[t]);
                })
                var fieldDatas = [];
                Object.keys(fields).forEach(f => {
                    var v = fields[f];
                    if (v && v != null) {
                        fieldDatas.push(f + "=" + fields[f]);
                    }
                })
                var body = tableName + "," + tagDatas.join(",") + ' ' + fieldDatas.join(",") + " " + timestampe;
                var url = aDbUrl + "/write";
                me.httpCall(url, "POST", {}, ps, body).then(res => {
                    success(res);
                })
            } catch (Exce) {
                console.log(Exce);
                success(null);
            }
        })
    },
    getRowContents(rows) {
        /* 
            row:{
                tableName,
                timestampe:ns,
                tags:{},
                fields:{}
            }
        */
        var me = this;
        var res = "";
        try {
            var items = [];
            for (var i = 0; i < rows.length; i++) {
                var r = rows[i];
                var tagContents = [];
                Object.keys(r.tags).forEach(tk => {
                    tagContents.push(tk + "=" + r.tags[tk]);
                });
                var fieldContents = [];
                Object.keys(r.fields).forEach(fk => {
                    fieldContents.push(fk + "=" + r.fields[fk]);
                });
                var content = r.tableName + "," +
                    tagContents.join(",") + " " +
                    fieldContents.join(",") + " " +
                    r.timestampe;
                items.push(content);
            }
            res = items.join("\n");
        } catch (Exce) {
            console.log(Exce);
        }
        return res;
    },
    writeBatchDB(aDbUrl, dbName, rows) {
        /* 
            row:{
                tableName,
                timestampe:ns,
                tags:{},
                fields:{}
            }
        */
        var me = this;
        return new Promise((success, faild) => {
            try {
                var content = me.getRowContents(rows);
                var fn = "/tmpdata/t_" + (new Date()).getTime() + ".txt";
                me.writeFile(fn, content);
                var cmdLine = 'curl -i -XPOST "' + aDbUrl + '/write?db=' + dbName + '" --data-binary @' + path.resolve(fn);
                me.runCmd(cmdLine).then(_ => {
                    fs.unlinkSync(path.resolve(fn));
                    success();
                })
            } catch (Exce) {
                console.log(Exce);
                success(null);
            }
        })
    },
    runCmd(cmdLine) {
        var me = this;
        return new Promise((success, faild) => {
            try {
                exec(cmdLine, function(error, stdout, stderr) {
                    console.log(stdout, stderr);
                    success();
                });

            } catch (Exce) {
                console.log(Exce);
                success(null);
            }
        })
    },


};
module.exports = {
    utils
}